package com.hp.bon.sgw.wkflow;

import org.springframework.beans.factory.annotation.Autowired;

import com.hp.bon.sgw.convert.DataExchangerImpl;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;
import com.hp.bon.sgw.wkflow.impl.AVP2XMLConvertVarObj;


public class BONFlowEngine {
	private WkflowDefParser wkFlowParser;

	/**
	 * 是否存在定义了工作流的Capability名字
	 * 
	 * @return
	 */
	public boolean hashCapabilityWorkflow(String capName) {
		return wkFlowParser.getAllFlowDefs().keySet().contains(capName);
	}

	public void init() {

	}

	public void startFlow(CallParam callParam) {
		try {
			String capability = DccAvpHelper.getCapability(callParam.getServiceContextId());
			FlowDef flowDef = wkFlowParser.getAllFlowDefs().get(capability);
			if (flowDef == null) {
				throw new RuntimeException("can't find flow def for capability:" + capability);
			}
			SGWFlowInstance flowInst = new SGWFlowInstance(flowDef);
			flowInst.setFlowExprParser(createFlowExpParser());
			callParam.setProcessor(flowInst);

      		flowInst.process(callParam);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private FlowExpressionParser createFlowExpParser() {
		FlowExpressionParser flowExprParser = new FlowExpressionParser();
		flowExprParser.addFlowVarObj("comAvp2XMLConvert", new AVP2XMLConvertVarObj(DataExchangerImpl.getInstance()));
		flowExprParser.init();
		return flowExprParser;
	}

	@Autowired
	public void setWkFlowParser(WkflowDefParser wkFlowParser) {
		this.wkFlowParser = wkFlowParser;
	}
}
